<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.9.0/vconsole.min.js"></script> -->
<!-- <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> -->

<body>

    <button onclick="startRecording()" id="startRecording">开始录音</button>
    <button onclick="stopRecording()" id="stopRecording" disabled>停止录音</button>
    <button onclick="playRecording()" id="playRecording" disabled>播放录音</button>
    <button onclick="downloadRecording()" id="downloadRecording" disabled>下载录音</button>
    <div>
        <audio src="" controls></audio>
    </div> 
    <script>
        // $(function () {
        //     var vConsole = new VConsole();
        //     checkAudio();
        // });

        var mediaRecorder;
        var recordedBlob = [];
        //window.onload = function () {
        //var vConsole = new VConsole();
        //checkAudio();
        // }
        // //检查当前浏览器是否支持当前格式的音频文件
        //var sourcetype = ['audio/wav', 'audio/ogg', 'audio/mpeg', 'audio/midi', 'audio/flac', 'audio/aac', 'audio/x-ms-wma', 'audio/aiff']
        // function checkAudio() {
        //     var myAudio = document.createElement("audio");
        //     if (myAudio.canPlayType) {
        //         //返回是或非或maybe
        //         sourcetype.forEach((item) => {
        //             if (myAudio.canPlayType(item) != '') {
        //                 document.write("您的浏览器支持:" + item + '<br>');
        //             }
        //         })
        //     }
        //     else {
        //         document.write("您的浏览器不支持要检测的音频格式。");
        //     }
        // }

        //开始录音
        function startRecording() {
            navigator.mediaDevices.getUserMedia({ audio: true })
                .then(function (stream) {
                    mediaRecorder = new MediaRecorder(stream);
                    //在停止录音时调用
                    mediaRecorder.ondataavailable = function (e) {
                        if (recordedBlob) {
                            recordedBlob.push(e.data);
                        } else {
                            recordedBlob = [e.data];
                        }
                    };
                    mediaRecorder.onstop = function (e) {
                        console.log("录音已停止");
                        const audioBlob = new Blob(recordedBlob, { type: 'audio/wav' });
                        console.log(audioBlob)
                        // 这里我们将得到的音频转换为ArrayBuffer用于后续加密
                        // handleAudioRecording(audioBlob);
                        recordedBlob = [];  // 清空缓存准备下一次录音
                    };
                    mediaRecorder.start();
                    document.getElementById('stopRecording').disabled = false;
                    document.getElementById('startRecording').disabled = true;
                })
                .catch(function (err) {
                    /* 处理error */
                    console.log("录音错误:", err);
                });
        }
        //停止录音
        function stopRecording() {
            if (mediaRecorder.state != "inactive") {
                mediaRecorder.stop();
                document.getElementById('playRecording').disabled = false;
                document.getElementById('downloadRecording').disabled = false;

                console.log(mediaRecorder)
                console.log(recordedBlob)

            }
        }
        //播放录音
        function playRecording() {

            var blob = new Blob(recordedBlob, { 'type': 'audio/wav' });
            //var blob = new Blob(recordedBlob, { type: "audio/ogg; codecs=opus" });
            var url = URL.createObjectURL(blob);
            var audio = new Audio(url);
            // var audio = document.createElement('audio');
            // audio.controls = true;
            // let sourcetype = ['audio/wav', 'audio/ogg', 'audio/mpeg', 'audio/midi', 'audio/flac', 'audio/aac', 'audio/x-ms-wma', 'audio/aiff']
            // sourcetype.forEach((item) => {
            //     let blob = new Blob(recordedBlob, { 'type': item });
            //     let url = URL.createObjectURL(blob);
            //     audio.innerHTML += `<source src=${url} type=${item}>`;
            // });
            audio.play();
            // audio.addEventListener("canplaythrough", event => {
            //     /* 音频可以播放；如果权限允许则播放 */
            //     audio.play();
            // });
        }

        // 录音加密
        async function handleAudioRecording(blob) {
            const arrayBuffer = await blob.arrayBuffer();

            // 生成密钥
            const key = await crypto.subtle.generateKey(
                { name: "AES-GCM", length: 256 },
                true,
                ["encrypt", "decrypt"]
            );

            // 准备IV (初始化向量)
            const iv = crypto.getRandomValues(new Uint8Array(12));

            // 加密配置
            const encryptedData = await crypto.subtle.encrypt(
                {
                    name: "AES-GCM",
                    iv: iv
                },
                key,
                arrayBuffer
            );

            // 将加密后的数据转回ArrayBuffer以便于传输或存储
            const encryptedArrayBuffer = new Uint8Array(encryptedData).buffer;

            // 处理加密后的数据...
            console.log("Encrypted data:", encryptedArrayBuffer);

            // 注意: 密钥和IV需要妥善保存，以便之后解密。
        }

        // 录音解密
        async function decryptAudio(encryptedData, key, iv) {
            // 将加密的数据转换为ArrayBuffer
            const encryptedArrayBuffer = new Uint8Array(encryptedData).buffer;

            try {
                // 使用相同的密钥和IV来解密
                const decryptedData = await crypto.subtle.decrypt(
                    {
                        name: "AES-GCM",
                        iv: iv
                    },
                    key,
                    encryptedArrayBuffer
                );

                // 转换为Blob以便于创建URL或者直接使用
                const decryptedBlob = new Blob([decryptedData], { type: 'audio/wav' });

                // 创建一个Object URL来播放音频
                const audioUrl = URL.createObjectURL(decryptedBlob);
                console.log("Decrypted audio URL:", audioUrl);

                // 如果你想自动播放这个音频，可以这样做：
                const audio = new Audio(audioUrl);
                audio.play();

                return decryptedBlob;  // 返回解密后的Blob以供进一步处理
            } catch (error) {
                console.error('Error during decryption:', error);
            }
        }

        // // 假设这是从加密部分得到的密钥和IV
        // const key = '' /* 密钥 */
        // const iv = '' /* IV */

        // // 假设这是加密后的音频数据
        // const encryptedData = /* 加密后的数据 */

        //     // 调用解密函数
        //     decryptAudio(encryptedData, key, iv);

        function downloadRecording() {
            var blob = new Blob(recordedBlob, { 'type': 'audio/wav' });
            var url = URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = 'recording.wav';
            a.click();
        }
   
   
    </script>

</body>

</html>